import { Injectable } from '@nestjs/common';
import { CreateUserAdminDto } from './dto/create-user-admin.dto';
import { UpdateUserAdminDto } from './dto/update-user-admin.dto';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { UserAdmin } from './entities/user-admin.entity';
import { formatError, formatSuccess } from 'src/util';
import * as md5 from 'md5';

@Injectable()
export class UserAdminService {
  constructor(
    @InjectRepository(UserAdmin)
    private readonly userAdminRepository: Repository<UserAdmin>,
  ) {}

  // 新增
  async create(createUserAdminDto: CreateUserAdminDto) {
    const userinfo = await this.findOne(createUserAdminDto.name);
    if (userinfo) return formatError({ msg: '用户名已存在' });
    createUserAdminDto.password = md5(createUserAdminDto.password);
    const data = await this.userAdminRepository.save(createUserAdminDto);
    return formatSuccess('新增成功');
  }

  // 通过用户名查找用户信息
  async findOne(username: string) {
    const data = await this.userAdminRepository.findOneBy({ name: username });
    return data;
  }
}
